package com.easy.frame.servers.sys.service.impl.area;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easy.frame.base.basic.constant.DbConstants;
import com.easy.frame.base.basic.pojo.vo.BaseTreeVO;
import com.easy.frame.base.service.tree.TreeHandler;
import com.easy.frame.base.service.tree.pageTree.PageTreeService;
import com.easy.frame.servers.sys.entity.area.SysArea;
import com.easy.frame.servers.sys.mapper.area.SysAreaMapper;
import com.easy.frame.servers.sys.service.area.SysAreaService;
import com.easy.frame.servers.sys.vo.SysAreaVO;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;

/**
 * 区域表 服务实现类
 *
 * @author tp
 * @since 2021-06-08
 */
@Service
public class SysAreaServiceImpl extends ServiceImpl<SysAreaMapper, SysArea> implements SysAreaService, PageTreeService<SysArea> {

    @Resource
    SysAreaMapper sysAreaMapper;

    @Override
    public BaseTreeVO getTree(int enabled, Long projectId, String name) {
        List<SysArea> entityList = list(new LambdaQueryWrapper<SysArea>()
                .eq(SysArea::getEnabled, enabled)
                .eq(SysArea::getProjectId, projectId)
                .eq(SysArea::getDeleted, DbConstants.DEFAULT_NO)
        );
        if (StringUtils.isEmpty(entityList)) {
            return null;
        }
        //set方式进行去重
        return TreeHandler.defaultInstance().getTree(new HashSet<>(getBaseTreeVO(name, entityList)));
    }

    @Override
    public SysArea add(SysArea sysArea) {
        return pageAdd(sysArea);
    }

    @Override
    public SysAreaVO clickAddOrg(Integer parentAreaId) {
        SysAreaVO sysAreaVO = new SysAreaVO();
        //首先默认为第一层级的分类
        int level = 1;
        SysAreaVO sysArea = new SysAreaVO();
        if (!StringUtils.isEmpty(parentAreaId)) {
            sysArea = sysAreaMapper.selectParentAreaById(parentAreaId);
            sysAreaVO.setCode(sysArea.getCode());
            sysAreaVO.setParentPath(sysArea.getPath());
            sysAreaVO.setName(sysArea.getName());
            level = sysArea.getLevel() + 1;
        }
        Integer maxSeq = sysAreaMapper.selectMaxSeq(sysArea.getPath(), level);
        sysAreaVO.setOrderNum(StringUtils.isEmpty(maxSeq) ? 10 : maxSeq / 10 * 10 + 10);
        sysAreaVO.setEnabled(DbConstants.DEFAULT_YES);
        return sysAreaVO;
    }
}
